package com.totoro.dubbo.properties;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Niki on 2018/7/4 8:46
 */
@Slf4j
public class Properties2Config {

    public static void properties2Config(Object propertiesObj, Object configObj) {
        if (propertiesObj == null || configObj == null) {
            return;
        }
        Class propertiesClass = propertiesObj.getClass();
        Class configClass = configObj.getClass();

        Field[] properties = propertiesClass.getDeclaredFields();
        if (properties == null || properties.length <= 0) {
            return;
        }
        for (Field field : properties) {
            try {
                Method setMethod = configClass.getDeclaredMethod(setMethod(field), field.getType());
                setMethod.invoke(configObj, field.get(propertiesObj));
            } catch (NoSuchMethodException e) {
                log.error("没有找到方法：{}",getMethod(field),e);
                continue;
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private static String getMethod(Field field) {
        String fieldName = field.getName();
        return "get" + upperCase(fieldName);
    }

    private static String setMethod(Field field) {
        String fieldName = field.getName();
        return "set" + upperCase(fieldName);
    }

    private static String upperCase(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }
}
